from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from common.Until import BlogDriver
#博客详情页测试用例
class BlogDetail:
    url = ""
    driver = ""
    def __init__(self):
        self.url = "http://127.0.0.1:8080/blog_detail.html?blogId=3565"
        self.driver = BlogDriver.driver
        self.driver.get(self.url)

    #登录状态下博客详情页的测试
    def DetailTestByLogin(self):
        #检查博客标题
        self.driver.find_element(By.CSS_SELECTOR,"body > div.container > div.right > div > div.title")
        #检查博客时间
        self.driver.find_element(By.CSS_SELECTOR,"body > div.container > div.right > div > div.date")
        #检查博客内容
        self.driver.find_element(By.CSS_SELECTOR,"#detail")
        #添加屏幕截图
        BlogDriver.getScreenShot()

    #登录状态下在博客详情页执行删除博客测试
    def DeleteBlogByLogin(self):
        self.driver.find_element(By.CSS_SELECTOR," body > div.container > div.right > div > div.operating > button:nth-child(2)").click()
        #注意显示等待只作用于当前那段代码
        wait = WebDriverWait(self.driver,2)
        wait.until(EC.alert_is_present())
        alert = self.driver.switch_to.alert
        #断言一下，检测是否符合预期
        assert alert.text == "确定删除这篇博客吗?"
        alert.accept()

        #获取当前页面的句柄
        curHandle = self.driver.current_window_handle
        #获取素有元素的句柄
        allHandLe = self.driver.window_handles
        #遍历所有元素的句柄，切换到新的页面
        for handle in allHandLe:
            if handle != curHandle:
                #执行切换句柄
                self.driver.switch_to.window(handle)

        title = self.driver.title
        url = self.driver.current_url
        print(title)
        print(url)

        #删除完成之后会自动跳转到博客列表页，此时可以访问第一条博客标题是否是指定标题
        text = self.driver.find_element(By.CSS_SELECTOR,"body > div.container > div.right > div:nth-child(1) > div.title").text
        #断言一下 -- 不是指定标题即测试通过
        assert text != "待删除博客"
